mui.init({
	//	preloadPages:[{
	//		id:'invest_record_page',
	//		url:'../invest_record/invest_record.html'
	//	}]
});
var old_back = mui.back;
mui.back = function() {
	// var btn = ["确定","取消"];
	//mui.confirm('确认关闭当前窗口？','提示',btn,function(e){
	//  if(e.index==0){
	plus.webview.getLaunchWebview().show();
	plus.webview.currentWebview().close();
	//  }
	// });
}

var hongbaoList = []; /*红包列表数组 {guid,money}*/

mui.plusReady(function() {
	var self = plus.webview.currentWebview();
	var formId = self.formId;
	var sessionId = plus.storage.getItem(KeyCfg.JSESSIONID);


	(function() {
		var targetPageId = plus.webview.currentWebview().id;
		plus.storage.setItem(KeyCfg.targetPageId, targetPageId);
		var buy_base_record = CmwMcore.$("buy_base_record");
		MeventMgr.onTouchstart(buy_base_record, function(event, self) {
			var cfg = {
				pars: {
					formId: formId
				}
			};
			MuiEventMgr.open('../buybase/buybase.html', cfg);
		});

		var buy_list_record = CmwMcore.$("buy_list_record");
		MeventMgr.onTouchstart(buy_list_record, function(event, self) {
			var cfd = {
				pars: {
					formId: formId
				}
			};
			MuiEventMgr.open('../buyrecord/buyrecord.html', cfd);
		});

		var recharge = CmwMcore.$('recharge');
		MeventMgr.onTouchstart(recharge, function(event, self) {
			MuiEventMgr.checkSessionByRemote(function(){
				MuiEventMgr.checkSecuityForwad(function() {
					MuiEventMgr.open('../recharge/recharge.html', {});
				});
			},function(){
				var win = plus.webview.getWebviewById(appid);
				win.evalJS("activeTabItemPage('userAccount');");
				window.setTimeout(function(){win.show();},1000);
			});
		});
	})();


	/*---- 初始化数据 ---*/
	(function initData() {
		var url = UrlConfig.minvest_buyDetail;
		var formDatas = {
			loanid: formId,
			sessionId: sessionId
		};
		MuiEventMgr.ajax(url, {
			pars: formDatas,
			sfn: function(data) {
				console.log(data);
				renderData(data);
			}
		});
	})();

	/**
	 * 将数据渲染到页面
	 * @param {Object} data
	 */
	function renderData(data) {
		var success = data.success;
		if (!success) return;
		var overTime = data.overTime;
		var loanState = data.loanState;
		var cashBalance = data.cashBalance;
		var hongbao = data.hongbao;
		hongbaoList = data.hongbaoList;
		var minBuyMoney = data.minBuyMoney;
		var id = data.id;
		var loanTitle = data.loanTitle;
		var thisIssueLoan = data.thisIssueLoan;
		var rateYear = data.rateYear;
		var rateYearDiscount = data.rateYearDiscount;
		var refundDeadline = data.refundDeadline;
		var residue = data.residue;
		var percent = data.percent;
		//新增用户信息
		var realName = data.realName;
		var sex = data.sex;
		var age = data.age;
		var qualifications = data.qualifications;
		var census = data.census;
		var workcity = data.workcity;
		var house = data.house;
		var car = data.car;
		var income = data.income;
		var workYear = data.workYear;
		var marry = data.marry;
		setVal2amount(data);
		$(".app_projects_item_progess_status").css("width", percent + "%");
		$("#loanId").val(id);
		$("#loan_title").text(loanTitle);
		$("#minBuyMoney").val(minBuyMoney);
		$("#loan_minBuyMoney").text(minBuyMoney + "起投");
		$("#loan_rateYear").text(rateYear + "%");
		$("#loan_rateYearDiscount").text("+" + rateYearDiscount + "%");
		$("#loan_refundDeadline").text(refundDeadline);
		$("#loan_overTime").text(overTime);
		$("#loan_loanState").text(loanState);
		$("#loan_percent").text(percent + "%");
		//用户信息页面传值
		$("#base_realName").text(realName);
		$("#base_sex").text(sex);
		$("#base_age").text(age);
		$("#base_qualifications").text(qualifications);
		$("#base_census").text(census);
		$("#base_workcity").text(workcity);
		$("#base_house").text(house);
		$("#base_car").text(car);
		$("#base_income").text(income);
		$("#base_workYear").text(workYear);
		$("#base_marry").text(marry);
		if (thisIssueLoan > 0) {
			thisIssueLoan = CmwMcore.getThousandths(thisIssueLoan);
		}
		$("#loan_thisIssueLoan").text("￥" + thisIssueLoan);
		if (!residue) residue = 0;
		$("#residue").val(residue);
		if (residue > 0) {
			residue = CmwMcore.getThousandths(residue);
		}
		$("#loan_residue").text(residue);

		if (!cashBalance) cashBalance = 0;
		$("#cashBalance").val(cashBalance);

		if (cashBalance > 0) {
			cashBalance = CmwMcore.getThousandths(cashBalance);
		}
		$("#loan_cashBalance").text(cashBalance);
		if (!hongbao || parseFloat(hongbao) <= 0) {
			hongbao = 0;
			$("#tr_hongbao").hide();
		} else {
			$("#tr_hongbao").show();
		}
		$("#sp_hongbao").text(hongbao);
		$("#loan_hongbao").val(hongbao);
		if (minBuyMoney && minBuyMoney > 0) {
			var j_ele = $('#amount');
			j_ele.attr("placeholder", '请输入不小于' + minBuyMoney + '的整数');
		}

		controlRight(loanState);
		//时间剩余
		var divTimeval = overTime;
		setInterval(function() {
			var showText = "";
			if (divTimeval <= 0) {
				$("#timeShow").html("0小时0分0秒");
				$("#buy_text").attr("disabled", true);
				return false;
			}
			//将秒数设置到显示区  
			var hh = parseInt(divTimeval / 3600);
			var mm = parseInt(divTimeval % 3600 / 60);
			var ss = divTimeval % 60;
			showText = hh + "小时" + mm + "分" + ss + "秒";
			$("#timeShow").html(showText);
			divTimeval = parseInt(divTimeval) - 1;
		}, 1000);

	}





	/**
	 * 为购买金额文本框赋值
	 * @param {Object} data
	 */
	function setVal2amount(data) {
		var cashBalance = data.cashBalance || "0";
		cashBalance = parseFloat(cashBalance);
		var minBuyMoney = data.minBuyMoney || "0";
		minBuyMoney = parseFloat(minBuyMoney);
		var residue = data.residue || "0";
		residue = parseFloat(residue);
		var ele_amount = $("#amount");
		if (residue <= minBuyMoney) {
			//			if(cashBalance < residue){
			//				ele_amount.val(cashBalance);
			//			}else{
			ele_amount.val(residue);
			//			}
			ele_amount.attr("readonly", "readonly");
		} else {
			ele_amount.removeAttr("readonly");
			ele_amount.val("");
		}
	}

	/**
	 * 权限控制
	 * @param {Object} overTime
	 */
	function controlRight(loanState) {
		if (loanState == '进行中') return;
		var a = $(".app_buy_inf");
		a.css("margin-top", "150px");
		var b = $(".buy-orange");
		b.css("color", "#606060");
		$("#app_buy_panel").hide();
	}

	/**
	 * 我要投标
	 */
	$("#btn_buy").click(function() {
		MuiEventMgr.checkSessionByRemote(function(){
			var dis=$("#btn_buy").attr("disabled")//判断是否有这属性
			if(dis)return; 
			var flag = validForm();
			if (!flag) return false;
			submitForm();			
		},function(){
			var win = plus.webview.getWebviewById(appid);
			win.evalJS("activeTabItemPage('userAccount');");
			window.setTimeout(function(){win.show();},1000);
		});
		return false;
	});

	/**
	 * 验证表单
	 */
	function validForm() {
		var flag = true;
		//amount,argee,hongbao
		//minBuyMoney,cashBalance,loan_hongbao
		var minBuyMoney = $("#minBuyMoney").val();
		var amount = $("#amount").val();
		var residue = $("#residue").val();
		var cashBalance = $("#cashBalance").val();
		var loan_hongbao = $("#loan_hongbao").val();
		if (!amount || isNaN(amount)) {
			mui.alert("请输入购买金额!");
			return false;
		}

		amount = parseFloat(amount);
		//		if(!cashBalance || parseFloat(cashBalance) <= 0){
		//			mui.alert("您的可用余额为0，请先充值后再购买!");
		//			return false;
		//		}
		var attr_readonly = $("#amount").attr("readonly");
		if (attr_readonly && attr_readonly == "readonly") { /*当可用余额或剩余额度小于最低投资金额时，后面就无须验证*/
			if (!$("input[name='agree']").is(":checked")) {
				mui.alert("您还没有同意《投资咨询与管理服务协议》!");
				return false;
			}
			//			return true;	 
		} else {
			if (amount < parseFloat(minBuyMoney)) {
				mui.alert("本标最低" + minBuyMoney + "元起投,请输入不低于" + minBuyMoney + "元的购买金额!");
				return false;
			}
		}


		if (amount > parseFloat(residue)) {
			mui.alert("输入的购买金额不能超出剩余额度!");
			return false;
		}

		if ($("input[name='hongbao']").is(":checked")) {
			var buyAmount = parseFloat(cashBalance) + parseFloat(loan_hongbao);
			if (amount > buyAmount) {
				mui.alert("可用余额不足，请先充值后再购买!");
				return false;
			}
		} else {
			if (amount > parseFloat(cashBalance)) {
				mui.alert("可用余额不足，请先充值后再购买!");
				return false;
			}
		}

		if (!$("input[name='agree']").is(":checked")) {
			mui.alert("您还没有同意《投资咨询与管理服务协议》!");
			return false;
		}
		return flag;
	}

	/**
	 * 当选中使用红包时，获取所有红包的ID
	 */
	function getHongbaoIds() {
		if (!hongbaoList || hongbaoList.length == 0) return;
		var arr = [];
		for (var i = 0, count = hongbaoList.length; i < count; i++) {
			var hongbaoObj = hongbaoList[i];
			var guid = hongbaoObj.guid;
			arr[i] = guid;
		}
		return arr.join();
	}

	/**
	 * 提交表单（买标）
	 */
	function submitForm() {
		CmwMcore.disabled('btn_buy');
		var url = UrlConfig.minvest_payAmountDetail;
		var amount = $("#amount").val();
		if ($("input[name='hongbao']").is(":checked")) {
			var _hongbaos = getHongbaoIds();
			var formDatas = {
				count: amount,
				hongbaos: _hongbaos
			};

			MuiEventMgr.ajax(url, {
				pars: formDatas,
				sfn: function(data) {
					var msg = data.content;
					msg = msg.replace("<br/>", "\n");
					saveDatas(msg, amount);
				},
				ffn: function() {
					CmwMcore.enabled('btn_buy');
				}
			});

		} else {
			var msg = "投标总金额：" + amount + "元,确认投标吗?";
			saveDatas(msg, amount);
		}
	}

	function saveDatas(msg, amount) {
		mui.confirm(msg, '来理财', {
			'确定': 'ok',
			'取消': 'no'
		}, function(e) {
			if (e.index == 0) {
				var hongbaos = '';
				if ($("input[name='hongbao']").is(":checked")) {
					hongbaos = getHongbaoIds();
				}
				var sessionId = plus.storage.getItem(KeyCfg.JSESSIONID);
				var userId = plus.storage.getItem(KeyCfg.userId);

				var url = UrlConfig.minvest_save;
				var loanId = $("#loanId").val();
				var formDatas = {
					loanid: loanId,
					count: amount,
					hongbaos: hongbaos,
					sessionId: sessionId,
					userId: userId
				};

				MuiEventMgr.ajax(url, {
					pars: formDatas,
					sfn: function(data) {
						CmwMcore.enabled('btn_buy');
						var msg = data.msg;
						var success = data.success;
						if (!success) {
							if (!msg) msg = "投标失败!";
							mui.alert(msg);
						} else {
							msg = "投标成功!";
							mui.alert(msg);
							var indexPage = plus.webview.getLaunchWebview();
							plus.storage.setItem(KeyCfg.currClickTabId, "invest");
							/*此处使用的HTML 原生 localStorage ，是因为在 invest.js 激活选项卡时是在 mui.init 初始化之前，故不能用 plus.storage*/
							localStorage.setItem(KeyCfg.invest_activeTabItem, "invest");
							indexPage.show();
							mui.fire(indexPage, 'refresh', {});
						}
					},
					ffn: function() {
						CmwMcore.enabled('btn_buy');
					}
				});
			} else {
				CmwMcore.enabled('btn_buy');
				return;
			}
		});
	}

	var a_mgr = CmwMcore.$("a_mgr");
	MeventMgr.onTouchstart(a_mgr, function(event, self) {
		var cfg = {
			pars: {}
		};
		MuiEventMgr.openBySafe('../mgrPro/mgrProtocol.html', cfg);
		return false;
	});

});